/*
 * packet.c
 *
 *  Created on: 2013. 10. 16.
 *      Author: jphong
 */


#include	"np.h"
#include	"packet.h"

/*
 * Make a packet
 * 		- type: packet type
 * 		- seq:  sequence number
 * 		- data: already loaded in pkt->data[]
 * 		- datalen: length of data in bytes
 */

Packet *
make_pkt(unsigned char type, unsigned char seq, Packet *pkt, int datalen)
{
	unsigned short	pktLength;

	pkt->header.type = type;
	pkt->header.seq = seq;
	pktLength = datalen + sizeof(Header);
	pkt->header.len = htons(pktLength);
	pkt->header.unused = 0;
	pkt->header.checksum = 0;	// Checksum field cleared before calcucation.
	pkt->header.checksum = in_cksum((uint16_t *) pkt, pktLength);
	return (pkt);
}

void print_pkt(const char *str, const Packet *pkt)
{
	unsigned int pktLength;
	static char	*typeName [] = {
		"NOOP", "DATA", "ACK", "END"
	};
	pktLength = ntohs(pkt->header.len);
	debug("%s %s:%d:%d:%x:%s\n", str, typeName[pkt->header.type], pkt->header.seq,
			pktLength, pkt->header.checksum,
			(pktLength > sizeof(Header)) ? &(pkt->data[0]) : "");
	return;
}

int isCorrupt(const Packet *pkt)
{
	return ( in_cksum( (uint16_t *) pkt, ntohs(pkt->header.len)) ); // returns 0 if no checksum error found
}

int isType(const Packet *pkt, unsigned char pktType, unsigned char seq)
{
	return ( (pkt->header.type == pktType) && (pkt->header.seq == seq) );
}
